<template>
  <div>
    <el-row :gutter="10" class="linkShowSearchCondition">
      <el-col :span="6" style="width:350px;">
        <div style="width:70px;display:inline-block;">起始日期：</div>
        <el-date-picker v-model="record.startTime" clearable type="datetime" style="margin-bottom:10px;" value-format='yyyy-MM-dd HH:mm:ss' size='small' placeholder="选择起始日期时间">
        </el-date-picker>
      </el-col>
      <el-col :span="6" style="width:350px;">
        <div style="width:70px;display:inline-block;">结束日期：</div>
        <el-date-picker v-model="record.endTime" clearable type="datetime" style="margin-bottom:10px;" value-format='yyyy-MM-dd HH:mm:ss' size='small' placeholder="选择结束日期时间">
        </el-date-picker>
      </el-col>
      <el-col :span="6" style="width:350px;">
        <div style="width:70px;display:inline-block;">所属模块：</div>
        <el-select v-model="record.mode" filterable clearable placeholder="请选择" style="width:220px;margin-bottom:10px;" size='small'>
          <el-option v-for="item in modesList" :key="item.name" :label="item.chinese_name" :value="item.name">
          </el-option>
        </el-select>
      </el-col>
      <el-col :span="6" style="width:350px;">
        <div style="width:70px;display:inline-block;">日志级别：</div>
        <el-select v-model="record.level" filterable clearable placeholder="请选择" style="width:220px;margin-bottom:10px;" size='small'>
          <el-option v-for="(item, key) in levelList" :key="key" :label="item" :value="key">
          </el-option>
        </el-select>
      </el-col>
      <el-col :span="6" style="width:350px;">
        <div style="width:70px;display:inline-block;">源地址：</div>
        <el-input v-emoji v-model="record.srcIp" style="width:220px;margin-bottom:10px;" size='small'></el-input>
      </el-col>
    </el-row>
    <div class="AuxiliarybuttonBox">
      <el-button type="success" size='small' @click="listData('init')">搜索</el-button>
      <el-button type="danger" size='small' @click="clearListData">清空日志</el-button>
      <!-- <el-button type="success" size='small' @click="exportSearchData()">导出日志</el-button> -->
    </div>
    <el-table ref="multipleTable" size='mini' :data="tableList" @sort-change='sortChange' tooltip-effect="dark" style="width: 100%">
      <el-table-column prop="TIME" align='center' label="时间" sortable='custom' :formatter="timeFormatter" min-width="150"></el-table-column>
      <el-table-column prop="MODE" align='center' label="模块" min-width="100">
        <template slot-scope="scope">
          {{ modeListShow(scope.row.MODE) || '' }}
        </template>
      </el-table-column>
      <el-table-column prop="LEVEL" align='center' sortable='custom' label="级别" min-width="80">
        <template slot-scope="scope">
          {{ levelList[scope.row.LEVEL] || '' }}
        </template>
      </el-table-column>
      <el-table-column prop="MSG" align='center' label="信息" min-width="400">
        <template slot-scope="scope">
          <tooltip :copyText="scope.row.MSG" class="wid190">
          </tooltip>
        </template>
      </el-table-column>
      <el-table-column prop="SIP" align='center' label="源地址" min-width="150">
        <template slot-scope="scope">
          <tooltip :copyText="scope.row.SIP" class="wid190">
          </tooltip>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="record.page" :page-size="record.limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
    </el-pagination>

    <save-dialog v-if="saveDialogVisible" ref="refSaveDialogVisible"></save-dialog>
  </div>
</template>

<script>
import { cleanMgmtLog, getMgmtMode, searchLog } from '@/api/system/oldLogData'
import SaveDialog from './components/SaveDialog'
import moment from 'moment'
export default {
  name: 'Managelog',
  components: {
    SaveDialog
  },
  data () {
    return {
      saveDialogVisible: false,
      record: {
        mode: '',
        level: '',
        startTime: '',
        endTime: '',
        srcIp: '',
        sort: '',
        order: '',
        page: 1,
        limit: 20
      },
      recordCopy: {
        mode: '',
        level: '',
        startTime: '',
        endTime: '',
        srcIp: '',
        sort: '',
        order: '',
        page: 1,
        limit: 20
      },
      total: 0,
      tableList: [],
      levelList: {
        '1': 'ERROR',
        '2': 'ALERT',
        '3': 'INFO',
        '4': 'DEBUG'
      },
      sortList: {
        'descending': 'desc',
        'ascending': 'asc'
      },
      modesList: null
      // modeList: {
      //   'monitor2alarm': '告警模块',
      //   'addr_object': '地址对象',
      //   'ipsec_vpn': 'IPSEC_VPN',
      //   'safe_zone': '安全区域',
      //   'AccessControl': '访问控制',
      //   'ddos_defense': 'FLOOD攻击防御',
      //   'dnat': 'DNAT',
      //   'content_filter': '深度过滤策略',
      //   'qos': '带宽管理',
      //   'sysconf': '配置管理',
      //   'alg': 'ALG',
      //   'app_id': '应用识别',
      //   'log_setting': '日志管理',
      //   'cli': '命令行',
      //   'statistic_flow': '流量统计',
      //   'nat64': 'NAT64',
      //   'upgrade': '系统升级',
      //   'app_object': '应用对象',
      //   'user_auth': '用户认证',
      //   'Vlan': '接口管理',
      //   'ips_policy': '入侵防御',
      //   'sys_manager': '设备管理',
      //   'ip_mac': 'IP-MAC绑定',
      //   'keyword_object': '关键字对象',
      //   'session_control': '连接控制',
      //   'service_object': '服务对象',
      //   'ipv6_tunnel': 'IPv6隧道',
      //   'flow_stats': '流量分析',
      //   'log': '日志查询',
      //   'session': '连接管理',
      //   'url_class': 'URL分类',
      //   'route_static': '静态路由',
      //   'admin': '管理员配置',
      //   'mac': '表项管理',
      //   'get_deinfo': '获取调试信息',
      //   'main_page': '首页',
      //   'mgmt_defense': '自身防护',
      //   'mgmt_log': '管理日志',
      //   'nat46': 'NAT46',
      //   'time_object': '时间对象',
      //   'config_assist': '辅助配置',
      //   'debug': '调试诊断',
      //   'route_policy': '策略路由',
      //   'url_policy': 'URL策略',
      //   'av_policy': '病毒策略',
      //   'bypass': 'BYPASS',
      //   'interface_collaboration': '接口联动',
      //   'run_mode': '运行模式',
      //   'ha': '双机热备',
      //   'snat': 'SNAT',
      //   'attack_defense': '异常报文攻击防御'
      // }
    }
  },
  created () {
    this.listData()
    getMgmtMode().then(res => {
      if (res.status === 0) {
        this.modesList = res.info
      }
    })
  },
  methods: {
    handleSizeChange (val) {
      // console.log(`每页 ${val} 条`)
      this.record.limit = val
      this.listData()
    },
    handleCurrentChange (val) {
      // console.log(`当前页: ${val}`)
      this.record.page = val
      this.listData()
    },
    listData (data) {
      if (data === 'init') {
        this.record.page = 1
      }
      let formData = Object.assign({}, this.record)
      searchLog(this.record).then(res => {
        if (res.status === 0) {
          // 解决低页面条数切换到高页面条数时，
          // 请求表单中使用低页面页数和高页面每页条数去请求数据，
          // 导致请求到的数据为空缺顶替了正常的请求数据。
          if (res.info.count !== 0) {
            let newLimit = Math.ceil(res.info.count / formData.limit)
            if (newLimit < formData.page) {
              return
            }
          }
          // ---------
          this.tableList = res.info.data
          this.total = res.info.count
        }
      })
    },
    dialogVisible () {
      this.saveDialogVisible = true
      this.$nextTick(() => {
        this.$refs.refSaveDialogVisible.init()
      })
    },
    clearListData () {
      this.$confirm('确定清空日志吗,清空日志需要一定时间！', '提示', {
        closeOnClickModal: false,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        confirmButtonClass: 'confirmButton',
        cancelButtonClass: 'confirmCancelButton',
        type: 'warning'
      }).then(() => {
        cleanMgmtLog().then(res => {
          this.$messages.success('清空成功')
          if (res.info === 1) {
            let reg = new RegExp('(?<=http:\\/\\/|https:\\/\\/)[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62}|(:[0-9]{1,6}))+\\.?', 'g')
            const hrefUrl = window.location.href.match(reg)
            let url = hrefUrl[0] + '/#/system/log/managelog'
            let path = window.location.protocol + '//' + url
            window.location.href = path
            window.location.reload()
          } else {
            this.listData()
          }
        })
      })
    },
    sortChange (column, prop, order) {
      if (column.order) {
        this.record.sort = column.prop
        this.record.order = this.sortList[column.order]
      } else {
        this.record.sort = ''
        this.record.order = ''
      }
      this.listData()
    },
    exportSearchData () {
      this.saveDialogVisible = true
      this.$nextTick(() => {
        this.$refs.refSaveDialogVisible.init(this.record)
      })
    },
    timeFormatter (data) {
      return moment(new Date(data.TIME * 1000)).format('YYYY-MM-DD HH:mm:ss')
    },
    modeListShow (mode) {
      if (this.modesList) {
        return this.modesList.filter(item => item.name === mode)[0] ? this.modesList.filter(item => item.name === mode)[0].chinese_name : ''
      }
    }
  }
}
</script>
